package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.AFileItem;
import com.sctvcloud.dongqu.beans.LiveItem;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.SearchResult;
import com.sctvcloud.dongqu.beans.TopicItem;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.MoreSearchResultAdapter;
import com.sctvcloud.dongqu.ui.adapter.SearchResultAdapter;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.KeyBoardUtils;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sctvcloud.dongqu.ui.activities.SearchActivity.REQUEST_CODE;

/**
 * 更多搜索
 */
public class MoreSearchActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.search_key_ct)
    protected CustomFontEditText search_ct;
    @BindView(R.id.search_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView search_result_list;
    @BindView(R.id.search_result_no_result)
    protected CustomFontTextView no_result;
    private int index = 0;
    private int count = 10;
    private LinearLayoutManager searchResultManager;
    private MoreSearchResultAdapter searchResultAdapter;
    private String keyword;
    private int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        keyword = getIntent().getStringExtra(EX_DATA);
        if (TextUtils.isEmpty(keyword)) {
            finish();
            return;
        }
        type = getIntent().getIntExtra(EX_TYPE, 0);
        if (type == 0) {
            finish();
            return;
        }
        initView();
    }

    private void initView() {
        search_ct.setText(keyword);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        searchResultManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        search_result_list.setLayoutManager(searchResultManager);
        search_result_list.addItemDecoration(new RBaseItemDecoration(0));
        search_result_list.setItemAnimator(new DefaultItemAnimator());
        search_ct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence.length() > 0) {
                    search_ct.setSelection(charSequence.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_special_more_search);
        ButterKnife.bind(this);
    }

    @OnClick(value = {R.id.search_speak_ll, R.id.search_speak_iv, R.id.search_cancel, R.id.tv_type_menu})
    public void speakClick(View view) {
        switch (view.getId()) {
            case R.id.search_speak_ll:
            case R.id.search_speak_iv:
                Intent speakIntent = new Intent(this, SpeakActivity.class);
//                search_ct.setText("");
                startActivityForResult(speakIntent, REQUEST_CODE);
                break;
            case R.id.search_cancel:
                finish();
                break;
        }
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            index++;
            searchForPage(keyword);
        }
    }

    @Override
    public void onRefresh() {
        index = 0;
        searchForPage(keyword);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            String voice = data.getStringExtra(SpeakActivity.SEARCH_KEY);
            if (!TextUtils.isEmpty(voice)) {
                search_ct.setText(voice);
                onRefresh();
//                addHistory(voice);
//                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//                pairs.add(new Pair<>("行为类型", "主动搜索"));
//                GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);
            }
        }
    }

    private void searchForPage(String keyword) {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", index);
        param.put("option", type);
        param.put("count", count);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null) {
                    JLog.e("=====search==" + fSearch.toString());
//                    pageAll=fSearch.getPageAll();
//                    currentPage=fSearch.getPageIndex();
//                    setSeaechData(fSearch);
                    setSeaechData(fSearch);
                } else {
                    no_result.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
    }


    private void setSeaechData(SearchResult fSearches) {
        List<TopicItem> specialList = fSearches.getSpecialList();
        List<LiveItem> liveList = fSearches.getLiveList();
        List<AFileItem> anchorList = fSearches.getAnchorList();
        List<IListShowData> tempList = new ArrayList<>();
        if (type == 2) {
            if (ListUtils.isListValued(specialList)) {
                if (specialList.size() >= 10) {
                    refreshLayout.setLoadMoreEnabled(true);
                } else {
                    refreshLayout.setLoadMoreEnabled(false);
                }
                tempList.addAll(specialList);
            }
        } else if (type == 3) {
            if (ListUtils.isListValued(liveList)) {
                if (liveList.size() >= 10) {
                    refreshLayout.setLoadMoreEnabled(true);
                } else {
                    refreshLayout.setLoadMoreEnabled(false);
                }
                tempList.addAll(liveList);
            }
        } else if (type == 4) {
            if (ListUtils.isListValued(anchorList)) {
                if (anchorList.size() >= 10) {
                    refreshLayout.setLoadMoreEnabled(true);
                } else {
                    refreshLayout.setLoadMoreEnabled(false);
                }
                tempList.addAll(anchorList);
            }
        }

        if (index == 0) {
            if (searchResultAdapter == null) {
                searchResultAdapter = new MoreSearchResultAdapter(this, tempList);
                search_result_list.setAdapter(searchResultAdapter);
            } else {
                searchResultAdapter.setData(tempList);
            }
        } else {
            int pos = searchResultAdapter.getItemCount();
            searchResultAdapter.addDatas(tempList);
            if (pos > 0) {
                searchResultAdapter.notifyItemChanged(pos - 1);
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            keyword = search_ct.getText().toString();
            if (TextUtils.isEmpty(keyword)) {
                toast("搜索关键词不能为空");
                return false;
            }
            refreshLayout.autoRefresh();
        }
        return super.dispatchKeyEvent(event);
    }
}
